require 'net/ssh'

class ServersController < ApplicationController
  active_scaffold :server do |config|
    config.label = "Servers Administration"
    config.columns = [:name, :address, :login, :password, :mysql_user, :mysql_password, :mysql_host, :description, :comments]
    config.list.columns = [:name, :address, :description, :comments]
    config.list.sorting = [{ :name => :asc }]
  end
  
  def ping
    @servers = Server.find :all
  end
  
  def pingserver
    @server = Server.find params[:id]
    strOut = ""
    data = IO.popen("ping -c 4 #{@server.address} 2>&1")
    strOut += data.readlines.join
    strOut += "<br /><br />"
    data = IO.popen("nmap -P0 -sT -p22 #{@server.address} 2>&1")
    strOut += data.readlines.join
    render(:update) do |page|
      page.replace_html "pingdatapre-#{@server.id}", strOut
    end
  end
  
  def run
    @scripts = Script.find :all
  end
  
  def run_execute
    @script = Script.find params[:script_id]
    @servers = Server.find(:all, :order => 'name asc')
  end
  
  def run_execute_on_server
    @server = Server.find params[:id]
    @script = Script.find params[:script_id]
    @results = []
    begin
      Net::SSH.start(@server.address, @server.login, @server.password) do |session|
        shell = session.shell.sync
        @script.commands.each do |line|
          if line.strip.length > 0
            line = line.chomp.gsub('@mysqlhost', @server.mysql_host).gsub('@mysqluser', @server.mysql_user).gsub('@mysqlpassword', @server.mysql_password)
            if (line.strip)[0..7] == "NOWAIT: " then
              logger.error "Anasychronously Executing : #{}"
              out = shell.send_data(line)
              logger.error "StdOut : Anasynchronous command."
              logger.error "StdErr : Anasynchronous command."
              logger.error "Status : Anasynchronous command."
              @results << { :command => line, :stdout => "Anasynchronous command.", :stderr => "Anasynchronous command.", :status => -1 }
            else
              logger.error "Executing : #{line}"
              out = shell.send_command(line)
              logger.error "StdOut : #{out.stdout.nil? ? "" : out.stdout[1..60]}"
              logger.error "StdErr : #{out.stderr.nil? ? "" : out.stderr[1..60]}"
              logger.error "Status : #{out.status}"
              @results << { :command => line, :stdout => out.stdout, :stderr => out.stderr, :status => out.status }
            end
          end
        end
        shell.exit
      end
    rescue StandardError => errObject
      @results = @results + [ { :command => "Error on ssh script processing", :stdout => "", :stderr => "Error executing SSH commands : \n"+errObject.inspect, :status => 1} ]
    end
  end
end
